﻿using System;
using System.Diagnostics; 
using System.Management;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using Microsoft.Win32;

namespace Lon.Util
{
   
    public class SystemInfoHelper
    {
        public static String GetCpuInfo()
        {
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_Processor");
            string cpuInfo = "";
            foreach (ManagementObject myobject in searcher.Get())
            {
                try
                {
                    string CS2 = cpuInfo;
                    cpuInfo = CS2 + myobject["Name"].ToString() + ",主频" + Math.Round((decimal)(decimal.Parse(myobject["MaxClockSpeed"].ToString()) / 1000M), 1).ToString() + "G/";
                }
                catch
                {
                }
            }
            return cpuInfo;
        }
        static PerformanceCounter _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");	
        //public static string GetCpuInfo()
        // {
           
        //     double d = GetCounterValue(_cpuCounter, "Processor", "% Processor Time", "_Total");
        //     return  d.ToString("F") + "%";
        // }
         public static string GetCPURate()
         {
           //  PerformanceCounter pc = new PerformanceCounter("Processor", "% Processor Time", "_Total");
           //  _cpuCounter.CategoryName = categoryName;
            // _cpuCounter.CounterName = counterName;
           //  _cpuCounter.InstanceName = instanceName;
             int CS1 = (int)_cpuCounter.NextValue();
         
             return (CS1.ToString() + "%");
         }
         static double GetCounterValue(PerformanceCounter pc, string categoryName, string counterName, string instanceName)
         {
             pc.CategoryName = categoryName;
             pc.CounterName = counterName;
             pc.InstanceName = instanceName;
             return pc.NextValue();
         }
         static String memCount="";
         public static string GetMemoryStatus()
         {
             if(String.IsNullOrEmpty(memCount))
             {
                 memCount  = QueryComputerSystem("totalphysicalmemory");
                 long val =long.Parse(memCount);
                 val = (val / 0x400) / 0x400;
                 memCount = val.ToString();
             }
             
             MEMORY_INFO MemInfo = new MEMORY_INFO();
             GlobalMemoryStatus(ref MemInfo);
//             long totalMb = (MemInfo.dwAvailPageFile/ 0x400) / 0x400;
             long totalMb = (MemInfo.dwTotalPhys / 0x400) / 0x400;
             long avaliableMb = (MemInfo.dwAvailPhys / 0x400) / 0x400;
//             long avaliableMb = (MemInfo.dwTotalPhys / 0x400) / 0x400;
             string temp = totalMb.ToString();
             //return MemInfo.dwMemoryLoad.ToString() + "%";
             return string.Concat(new object[] { "", memCount, "MB/", MemInfo.dwMemoryLoad, "%" });
         }
         static public string QueryComputerSystem(string type)
         {
             string str = null;
             ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
             foreach (ManagementObject objMgmt in objCS.Get())
             {
                 str = objMgmt[type].ToString();
             }
             return str;
         }
         public static List<DiskInfoStruct> GetDiskInfo()
         {
             List<DiskInfoStruct> lDiskInfo=new List<DiskInfoStruct>();
             try
             {
                 ManagementObjectCollection moCollection = new ManagementClass("Win32_LogicalDisk").GetInstances();
                 foreach (ManagementObject mObject in moCollection)
                 {
                     if (int.Parse(mObject["DriveType"].ToString()) == 3)
                     {
                         DiskInfoStruct diskInfoStruct;
                         diskInfoStruct.strDiskName = mObject["Name"].ToString();
                         if (mObject["VolumeName"]!=null)
                         {
                             diskInfoStruct.strVolumeName = mObject["VolumeName"].ToString();
                             diskInfoStruct.lDiskSize = long.Parse(mObject["Size"].ToString());
                             diskInfoStruct.lDiskFreeSpace = long.Parse(mObject["FreeSpace"].ToString());
                             diskInfoStruct.strDiskFileSystem = mObject["FileSystem"].ToString();
                             lDiskInfo.Add(diskInfoStruct);
                         }
                         else
                         {
                             diskInfoStruct.strVolumeName = "";
                         }
                         
                         
                     }
                 }
             }
             catch (System.Exception ex)
             {
             	
             }
            
             return lDiskInfo;
         }

         public static List<string> GetDiskState()
         {
             List<string> disksList = new List<string>();
             string diskInfo = "";
             List<DiskInfoStruct> lDiskInfo = GetDiskInfo();
             foreach (DiskInfoStruct dis in lDiskInfo)
             {
                 diskInfo = string.Concat(new object[] { "[", dis.strDiskName, "盘]", (dis.lDiskSize / 0x400) / 0x400, "MB/", 100 - ((int)(((((float)dis.lDiskFreeSpace) / 1f) / ((float)dis.lDiskSize)) * 100f)), "%\n" });
                 disksList.Add(diskInfo);
             }
             return disksList;
         }

         public static bool HaveSoundCard()
         {
             ManagementObjectSearcher seacher = new ManagementObjectSearcher("SELECT * FROM Win32_SoundDevice");
             if (seacher.Get().Count == 0)
             {
                 return false;
             }
             return true;
         }

 
         public static List<string> GetSpeechVoiceTakenKeys(out String DefaultTokenId, out int DefaultTTSRate,out String saveVoice)
         {

             DefaultTTSRate = 0;
             DefaultTokenId = "";
             RegistryKey LocalMachine = Registry.LocalMachine;
             RegistryKey CurrentUser = Registry.CurrentUser;
             RegistryKey key = LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Speech\Voices\Tokens");
             string[] keys = key.GetSubKeyNames();
             key.Close();
             List<string> keylist = new List<string>();
             saveVoice = "";
             foreach (string s in keys)
             {
                 key = LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Speech\Voices\Tokens\" + s + @"\Attributes");
                 if (key != null)
                 {
                     if (key.GetValue("Language").ToString().StartsWith("804"))
                     {
                         keylist.Add(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\" + s);
                     }
                     if (key.GetValue("Language").ToString() == "804")
                     {
                         saveVoice = @"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\" + s;
                     }
                     key.Close();
                 }
             }
             if (keylist.Count ==0)
             {
                 return keylist;
             }
   
             key = CurrentUser.OpenSubKey(@"Software\Microsoft\Speech\Voices", true);
   
             if (key != null)
             {
                 object obj = key.GetValue("DefaultTokenId");
                 if (obj != null)
                 {
                     DefaultTokenId = obj.ToString();
                 }
                 obj = key.GetValue("DefaultTTSRate");
                 if (obj != null)
                 {
                     DefaultTTSRate = (int)obj;
                 }
                 if (!(keylist.Contains(DefaultTokenId) || (keylist.Count <= 0)))
                 {
                     key.SetValue("DefaultTokenId", keylist[0]);
                     DefaultTokenId = keylist[0];
                 }
                 if (DefaultTTSRate < 5)
                 {
                     key.SetValue("DefaultTTSRate", 5);
                 }
                 key.Close();
             }
             return keylist;
         }

       
         [DllImport("kernel32")]
         public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);



         public static string GetComputerName()
         {
             string value = "";
             using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0"))
             {
                 value = regKey.GetValue("ProcessorNameString", "x86 Family").ToString().Trim();
                 regKey.Close();
             }
             return value;
         }

         public static string GetSytemVerMessage()
         {
             string str = null;
             ManagementObjectSearcher objCS = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
             foreach (ManagementObject objMgmt in objCS.Get())
             {
                 str = objMgmt["Version"].ToString();
             }
             return str;
         }

         
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct MEMORY_INFO
    {
        public uint dwLength;
        public uint dwMemoryLoad;
        public uint dwTotalPhys;
        public uint dwAvailPhys;
        public uint dwTotalPageFile;
        public uint dwAvailPageFile;
        public uint dwTotalVirtual;
        public uint dwAvailVirtual;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct DiskInfoStruct
    {
        public string strDiskName;
        public string strVolumeName;
        public long lDiskSize;
        public long lDiskFreeSpace;
        public string strDiskFileSystem;
    }
 
}

